#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 29 13:47:54 2018

@author: jili
"""
from jili.core.printlog import print
from jili.core.convert import converttype
import pandas as pd
class text():
    def __init__(self,title=""):
        
        self.title=title
        self.body=[]
        self.url=""
    def sethead(self,title):
        self.title=title
        return self
    def __head(self):
        return """"<html>
            <head>
                <meta charset="utf-8">
                <title>"""+self.title+"""</title>
            </head>
            <body>"""
    def end(self):
        return """
                </body>
            <html>"""
    def addtext(self,text,headtype="h4"):
        a= """<div align="center">
                <"""+headtype+""" align="center">"""+text+"""</"""+headtype+""">
            </div>"""
        self.body.append(a)
        return self
    def addtable(self,table):
        if not isinstance(table,pd.DataFrame):
            t=converttype(table,"df")
        else:
            t=table
        if isinstance(t,pd.DataFrame):
            pd.set_option('max_colwidth',200)
            a =t.to_html()
            a= """<div align="center">
                    """+a+"""
                </div>"""
        else:
            a=""
        self.body.append(a)
        return self
    def addfig(self,fig):
        a= """<div align="center">
                <img src="""+fig+"""  alt="no fig" />
            </div>"""
        self.body.append(a)
        return self
    def to_string(self):
        h=self.__head()
        for i in self.body:
            h=h+i
        h=h+self.end()
        return h
def sendtext(subject,text,fig=[],tomail=[],attachfile=[]):
    msg = "<html><head>HI Jili</head><body><p>I am your  Monitoring Assistant</p><p>"+text+"</p></body></html>"
    send(subject,msg,fig,tomail,attachfile)
def send(subject,msg,fig=[],tomail=[],attachfile=[]):
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage 

    # 发送邮件的相关信息，根据你实际情况填写
    smtpHost = 'smtp.163.com'
    sslPort = '465'
    fromMail = 'nchengci@163.com'
    username = 'nchengci@163.com'
    password = 'wy54jili'
    toMail = ['nchjili@qq.com','nchengci@163.com']
    #msg = "<html><head>HI Jili</head><body><p>I am your  Monitoring Assistant</p><p>"+msg+"</p></body></html>"
    if attachfile:
        mail = MIMEMultipart('mixed') 
        mail['Subject'] = subject
        mail['From'] = fromMail
        if tomail:
            if isinstance(tomail,list):
              mail['To'] =";".join(tomail)
            else:
              mail['To'] =tomail
        else:
            mail['To'] =toMail
        # 邮件正文内容
        mail.attach(MIMEText(msg, 'html', 'utf-8'))
        #增加图片
        if fig:
            if isinstance(fig,list):
                for i in fig:
                    file = open(i, "rb")
                    img_data = file.read()
                    file.close()
                    img = MIMEImage(img_data)
                    img.add_header('Content-ID','<image1>')
                    img["Content-Disposition"] = 'attachment; filename="'+i+ '"'
                    mail.attach(img)
            else:
                file = open(fig, "rb")
                img_data = file.read()
                file.close()
                img = MIMEImage(img_data)
                img.add_header('Content-ID','<image1>')
                img["Content-Disposition"] = 'attachment; filename="'+fig+ '"'
                mail.attach(img)
        # 构造附件（附件为txt格式的文本）
        if isinstance(attachfile,list):
          for i in attachfile:
            att = MIMEText(open(i, 'rb').read(), 'base64', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            n=len(i)
            m=i.rfind("/")+1
            attachname=i[m:n]
            att["Content-Disposition"] = 'attachment; filename="'+attachname+ '"'
            mail.attach(att)
        else:
          att = MIMEText(open(attachfile, 'rb').read(), 'base64', 'utf-8')
          att["Content-Type"] = 'application/octet-stream'
          n=len(attachfile)
          m=attachfile.rfind("/")+1
          attachname=attachfile[m:n]
          att["Content-Disposition"] = 'attachment; filename="'+attachname+'"'
          mail.attach(att)
    else:
        if fig:
            mail = MIMEMultipart('mixed') 
            mail['Subject'] = subject
            mail['From'] = fromMail
            if tomail:
                if isinstance(tomail,list):
                  mail['To'] =";".join(tomail)
                else:
                  mail['To'] =tomail
            else:
                mail['To'] =toMail
            # 邮件正文内容
            mail.attach(MIMEText(msg, 'html', 'utf-8'))
            if isinstance(fig,list):
                for i in fig:
                    file = open(i, "rb")
                    img_data = file.read()
                    file.close()
                    img = MIMEImage(img_data)
                    img.add_header('Content-ID','<image1>')
                    img["Content-Disposition"] = 'attachment; filename="'+i+ '"'
                    mail.attach(img)
            else:
                file = open(fig, "rb")
                img_data = file.read()
                file.close()
                img = MIMEImage(img_data)
                img.add_header('Content-ID','<image1>')
                img["Content-Disposition"] = 'attachment; filename="'+fig+ '"'
                mail.attach(img)
        else:
            mail = MIMEText(msg, 'html', 'utf-8')
            mail['Subject'] = subject
            mail['From'] = fromMail
            if tomail=="":
                mail['To'] =toMail
            else:
                if isinstance(tomail,list):
                  mail['To'] =";".join(tomail)
                else:
                  mail['To'] =tomail
    try:
        smtp = smtplib.SMTP_SSL(smtpHost,sslPort)
        smtp.ehlo()
        smtp.login(username,password)
        smtp.sendmail(fromMail, toMail, mail.as_string())
        smtp.close()
    except smtplib.SMTPRecipientsRefused:
      print('Recipient refused')
      smtp.close()
    except smtplib.SMTPAuthenticationError:
      print('Auth error')
      smtp.close()
    except smtplib.SMTPSenderRefused:
      print('Sender refused')
      smtp.close()
    except smtplib.SMTPException as e:
      print(e)
      smtp.close()
def sendhtml(subject,htmlfile,tomail=[],attachfile=[]):
    htmlf=open(htmlfile,'r',encoding="utf-8")
    htmlcont=htmlf.read()
    send(subject,htmlcont,tomail,attachfile)